<template>
  <div class="ordering-page">
    <el-row :gutter="20">
      <!-- 菜品展示区 -->
      <el-col :xs="24" :sm="24" :md="18" :lg="18" :xl="18">
        <div class="dishes-section">
          <div class="section-header">
            <h2>菜品列表</h2>
            <el-input
              v-model="searchQuery"
              placeholder="搜索菜品..."
              class="search-input"
              clearable
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
          </div>
          <el-row :gutter="20">
            <el-col 
              v-for="dish in filteredDishes" 
              :key="dish.id" 
              :xs="24" 
              :sm="12" 
              :md="8" 
              :lg="8" 
              :xl="8"
              class="dish-card"
            >
              <el-card 
                class="dish-card-content"
                :class="{ 'selected': getQuantity(dish.id) > 0 }"
              >
                <div class="dish-info">
                  <h3>{{ dish.name }}</h3>
                  <p class="price">¥{{ dish.price }}</p>
                  <p class="description">{{ dish.description }}</p>
                  <div class="quantity-control">
                    <el-button 
                      type="danger" 
                      :icon="Minus" 
                      circle 
                      @click="decreaseQuantity(dish.id)"
                      :disabled="!getQuantity(dish.id)"
                    />
                    <span class="quantity">{{ getQuantity(dish.id) }}</span>
                    <el-button 
                      type="success" 
                      :icon="Plus" 
                      circle 
                      @click="increaseQuantity(dish.id)"
                    />
                  </div>
                </div>
              </el-card>
            </el-col>
          </el-row>
        </div>
      </el-col>

      <!-- 订单信息区 -->
      <el-col :xs="24" :sm="24" :md="6" :lg="6" :xl="6">
        <div class="order-section">
          <el-card class="order-card">
            <template #header>
              <div class="order-header">
                <h3>我的订单</h3>
                <el-button 
                  type="primary" 
                  @click="submitOrder"
                  :disabled="selectedItems.length === 0"
                >
                  提交订单
                </el-button>
              </div>
            </template>
            
            <div class="order-items">
              <div 
                v-for="item in selectedItems" 
                :key="item.id" 
                class="order-item"
              >
                <span class="item-name">{{ item.name }}</span>
                <div class="item-details">
                  <span class="item-quantity">x{{ item.quantity }}</span>
                  <span class="item-price">¥{{ item.price * item.quantity }}</span>
                </div>
              </div>
            </div>

            <div class="order-total">
              <span>总计：</span>
              <span class="total-amount">¥{{ totalAmount }}</span>
            </div>

            <!-- 进行中的订单 -->
            <div class="active-orders">
              <div class="orders-header">
                <h4>进行中的订单</h4>
                <el-button 
                  type="text"
                  @click="refreshOrders"
                >
                  刷新
                </el-button>
              </div>
              <div v-if="activeOrders.length === 0" class="empty-orders">
                暂无进行中的订单
              </div>
              <div v-else class="orders-list">
                <div 
                  v-for="order in activeOrders" 
                  :key="order.id" 
                  class="order-card-item"
                >
                  <div class="order-card-header">
                    <el-tag :type="getStatusType(order.status)" size="small">
                      {{ getStatusText(order.status) }}
                    </el-tag>
                  </div>
                  <div class="order-card-info">
                    <span class="order-card-amount">¥{{ order.totalAmount }}</span>
                    <div class="order-card-actions">
                      <el-button 
                        v-if="order.status === 0"
                        type="success" 
                        size="small"
                        @click="payOrder(order.id)"
                      >
                        结账
                      </el-button>
                      <el-button 
                        v-if="order.status === 0"
                        type="danger" 
                        size="small"
                        @click="cancelOrder(order.id)"
                      >
                        取消
                      </el-button>
                      <el-button 
                        type="primary" 
                        size="small"
                        @click="showOrderDetail(order.id)"
                      >
                        详情
                      </el-button>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </el-card>
        </div>
      </el-col>
    </el-row>

    <!-- Order Detail Dialog -->
    <el-dialog
      v-model="detailDialogVisible"
      title="订单详情"
      width="50%"
    >
      <div v-if="orderDetail" class="order-detail">
        <div class="detail-item">
          <span class="label">订单编号：</span>
          <span>{{ orderDetail.order.orderNo }}</span>
        </div>
        <div class="detail-item">
          <span class="label">状态：</span>
          <el-tag :type="getStatusType(orderDetail.order.status)">
            {{ getStatusText(orderDetail.order.status) }}
          </el-tag>
        </div>
        <div class="detail-item">
          <span class="label">创建时间：</span>
          <span>{{ formatTime(orderDetail.order.createTime) }}</span>
        </div>
        <div class="detail-item">
          <span class="label">更新时间：</span>
          <span>{{ formatTime(orderDetail.order.updateTime) }}</span>
        </div>
        <div class="detail-items">
          <h4>订单菜品</h4>
          <div 
            v-for="item in orderDetail.details" 
            :key="item.id" 
            class="detail-item"
          >
            <span class="item-name">{{ item.dishName }}</span>
            <span class="item-quantity">x{{ item.quantity }}</span>
            <span class="item-price">¥{{ item.dishPrice }}</span>
          </div>
        </div>
        <div class="detail-item total">
          <span class="label">总金额：</span>
          <span class="total-amount">¥{{ orderDetail.totalAmount }}</span>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Minus, Search } from '@element-plus/icons-vue'
import { dishApi, orderApi } from '../api'

// State
const dishes = ref([])
const quantities = ref({})
const searchQuery = ref('')

// Computed
const filteredDishes = computed(() => {
  if (!searchQuery.value) return dishes.value
  const query = searchQuery.value.toLowerCase()
  return dishes.value.filter(dish => 
    dish.name.toLowerCase().includes(query) ||
    dish.description.toLowerCase().includes(query)
  )
})

const selectedItems = computed(() => {
  return dishes.value
    .filter(dish => quantities.value[dish.id] > 0)
    .map(dish => ({
      ...dish,
      quantity: quantities.value[dish.id]
    }))
})

const totalAmount = computed(() => {
  return selectedItems.value.reduce((total, item) => {
    return total + item.price * item.quantity
  }, 0)
})

// Order related state
const activeOrders = ref([])
const detailDialogVisible = ref(false)
const orderDetail = ref(null)

// Methods
const loadDishes = async () => {
  try {
    const response = await dishApi.getDishes()
    dishes.value = response.data
    // 初始化数量为0
    dishes.value.forEach(dish => {
      quantities.value[dish.id] = 0
    })
  } catch (error) {
    ElMessage.error('加载菜品列表失败')
  }
}

const getQuantity = (dishId) => {
  return quantities.value[dishId] || 0
}

const increaseQuantity = (dishId) => {
  quantities.value[dishId] = (quantities.value[dishId] || 0) + 1
}

const decreaseQuantity = (dishId) => {
  if (quantities.value[dishId] > 0) {
    quantities.value[dishId]--
  }
}

const submitOrder = async () => {
  try {
    const dishIds = []
    const quantitiesList = []
    
    Object.entries(quantities.value).forEach(([dishId, quantity]) => {
      if (quantity > 0) {
        dishIds.push(Number(dishId))
        quantitiesList.push(quantity)
      }
    })

    if (dishIds.length === 0) {
      ElMessage.warning('请至少选择一个菜品')
      return
    }

    await orderApi.createOrder(dishIds, quantitiesList)
    ElMessage.success('订单创建成功')
    // 清空选择
    Object.keys(quantities.value).forEach(key => {
      quantities.value[key] = 0
    })
    // 刷新订单列表
    await loadActiveOrders()
  } catch (error) {
    ElMessage.error('创建订单失败')
  }
}

// Order related methods
const loadActiveOrders = async () => {
  try {
    const response = await orderApi.getOrderList(1, 20, 0) // 增加到20条
    activeOrders.value = response.data.records
  } catch (error) {
    ElMessage.error('加载订单列表失败')
  }
}

const refreshOrders = () => {
  loadActiveOrders()
}

const showOrderDetail = async (id) => {
  try {
    const response = await orderApi.getOrderDetail(id)
    orderDetail.value = response.data
    detailDialogVisible.value = true
  } catch (error) {
    ElMessage.error('获取订单详情失败')
  }
}

const payOrder = async (id) => {
  try {
    await orderApi.payOrder(id)
    ElMessage.success('结账成功')
    loadActiveOrders()
  } catch (error) {
    ElMessage.error('结账失败')
  }
}

const cancelOrder = async (id) => {
  try {
    await ElMessageBox.confirm('确定要取消这个订单吗？', '提示', {
      type: 'warning'
    })
    await orderApi.cancelOrder(id)
    ElMessage.success('订单已取消')
    loadActiveOrders()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('取消订单失败')
    }
  }
}

const getStatusType = (status) => {
  switch (status) {
    case 0:
      return 'warning'
    case 1:
      return 'success'
    case 2:
      return 'info'
    default:
      return ''
  }
}

const getStatusText = (status) => {
  switch (status) {
    case 0:
      return '待结账'
    case 1:
      return '已结账'
    case 2:
      return '已取消'
    default:
      return status
  }
}

const formatTime = (timeString) => {
  if (!timeString) return ''
  const date = new Date(timeString)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit',
    hour12: false
  })
}

// Lifecycle
onMounted(() => {
  loadDishes()
  loadActiveOrders()
})
</script>

<style scoped>
.ordering-page {
  padding: 20px;
  min-height: 100vh;
}

.dishes-section {
  margin-bottom: 20px;
}

.section-header {
  display: flex;
  flex-direction: column;
  gap: 15px;
  margin-bottom: 20px;
}

@media (min-width: 768px) {
  .section-header {
    flex-direction: row;
    justify-content: space-between;
    align-items: center;
  }
}

.search-input {
  width: 100%;
}

@media (min-width: 768px) {
  .search-input {
    width: 300px;
  }
}

.dishes-section h2 {
  margin: 0;
  color: #333;
  font-size: 24px;
}

.dish-card {
  margin-bottom: 20px;
}

.dish-card-content {
  transition: all 0.3s;
  cursor: pointer;
  height: 100%;
}

.dish-card-content:hover {
  transform: translateY(-5px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.dish-card-content.selected {
  border: 2px solid #409EFF;
}

.dish-info {
  padding: 14px;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.dish-info h3 {
  margin: 0 0 10px 0;
  font-size: 16px;
}

.price {
  color: #f56c6c;
  font-size: 18px;
  font-weight: bold;
  margin: 10px 0;
}

.description {
  color: #666;
  font-size: 14px;
  margin: 10px 0;
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.quantity-control {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-top: 10px;
}

.quantity {
  min-width: 30px;
  text-align: center;
  font-weight: bold;
}

.order-section {
  position: sticky;
  top: 20px;
}

.order-card {
  height: calc(100vh - 100px);
  display: flex;
  flex-direction: column;
}

.order-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.order-items {
  flex: 1;
  overflow-y: auto;
  padding: 10px 0;
}

.order-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 0;
  border-bottom: 1px solid #eee;
}

.item-name {
  flex: 1;
  font-weight: bold;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.item-details {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-left: 10px;
}

.item-quantity {
  color: #666;
}

.item-price {
  color: #f56c6c;
  font-weight: bold;
  min-width: 60px;
  text-align: right;
}

.order-total {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  margin-top: 20px;
  padding-top: 20px;
  border-top: 2px solid #eee;
}

.total-amount {
  color: #f56c6c;
  font-size: 24px;
  font-weight: bold;
  margin-left: 10px;
}

.active-orders {
  margin-top: 20px;
  border-top: 1px solid #eee;
  padding-top: 20px;
}

.orders-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.orders-header h4 {
  margin: 0;
  font-size: 16px;
}

.empty-orders {
  text-align: center;
  color: #999;
  padding: 20px;
}

.orders-list {
  max-height: 400px; /* 增加显示高度 */
  overflow-y: auto;
}

.order-card-item {
  padding: 10px;
  border: 1px solid #eee;
  border-radius: 4px;
  margin-bottom: 8px;
}

.order-card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 5px;
}

.order-card-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.order-card-amount {
  color: #f56c6c;
  font-weight: bold;
}

.order-card-actions {
  display: flex;
  gap: 5px;
}

.order-card-actions .el-button {
  padding: 4px 8px;
  font-size: 12px;
}

.order-detail {
  padding: 20px;
}

.detail-item {
  margin-bottom: 15px;
  display: flex;
  align-items: center;
}

.detail-item .label {
  width: 80px;
  color: #666;
}

.detail-items {
  margin-top: 20px;
}

.detail-items h4 {
  margin-bottom: 15px;
}

.detail-item.total {
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #eee;
}

.total-amount {
  color: #f56c6c;
  font-weight: bold;
  font-size: 18px;
}

/* 移动端适配 */
@media (max-width: 768px) {
  .ordering-page {
    padding: 10px;
  }

  .dish-card-content {
    margin-bottom: 10px;
  }

  .order-section {
    position: static;
    margin-top: 20px;
  }

  .order-card {
    height: auto;
  }

  .item-details {
    flex-direction: column;
    align-items: flex-end;
    gap: 5px;
  }

  .order-total {
    margin-top: 15px;
    padding-top: 15px;
  }

  .total-amount {
    font-size: 20px;
  }
}
</style> 